package com.bigfire.dtm.core.query.handler.user;

import com.bigfire.dtm.core.event.repository.user.UserDataHandler;
import com.bigfire.dtm.dal.entity.user.UserInfoEntry;
import com.bigfire.dtm.domain.user.command.QueryUserByIdCommand;
import com.bigfire.dtm.domain.user.command.QueryUserByIdsCommand;
import com.bigfire.dtm.domain.user.command.QueryUserByTenantIdCommand;
import com.bigfire.dtm.domain.user.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import org.axonframework.queryhandling.QueryHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 用户相关数据查询功能处理服务
 * @author Damon S.
 * @version v1.0.1
 * @date 2019年11月07日 18:10
 */
@Component
//@RequiredArgsConstructor
public class UserQueryHandler {

    private final UserDataHandler dataHandler;
    private final UserInfoTranslator translator;

    public UserQueryHandler(UserDataHandler dataHandler, UserInfoTranslator translator) {
        this.dataHandler = dataHandler;
        this.translator = translator;
    }

    @SuppressWarnings("unused")
    @QueryHandler
    private List<UserInfoVO> handle(QueryUserByTenantIdCommand command) {
        if (Objects.isNull(command.getTenantId())) {
            return Collections.emptyList();
        }
        // 查询指定用户的下级数据项
        List<UserInfoEntry> entries =
                dataHandler.findUserByTenantId(command.getTenantId());
        if (CollectionUtils.isEmpty(entries)) {
            return Collections.emptyList();
        }
        return translator.toUserInfos(entries);
    }

    @SuppressWarnings("unused")
    @QueryHandler
    private UserInfoVO handle(QueryUserByIdCommand command) {
        if (Objects.isNull(command.getUserId())) {
            return UserInfoVO.EMPTY;
        }
        // 查询指定用户数据项
        return translator.toUserInfo(
                dataHandler.findUserById(command.getUserId())
        );
    }

    @SuppressWarnings("unused")
    @QueryHandler
    private List<UserInfoVO> handle(QueryUserByIdsCommand command) {
        if (CollectionUtils.isEmpty(command.getUserIds())) {
            return Collections.emptyList();
        }
        return translator.toUserInfos(
                dataHandler.findUserByIds(command.getUserIds())
        );
    }
}
